﻿/* 功能:  用户管理
 * 创建人：Kencery  创建时间：2017-12-9
 */
var ml = window.ml || {};
ml.admin = ml.admin || {};

ml.admin.user = (function () {
    var defaults = {
        listUrl: "/User/List",
        getuserTypeUrl: '/Common/GetUserType',
        getuserTypeAllUrl: '/Common/GetUserTypeAll',
        getAddRessByUserIdUrl: "/User/GetAddRessByUserId",
        getUserInvitationByUserIdUrl: "/User/GetUserInvitationByUserId",
        getById: "/User/GetById",
        uploadUrl: "/Common/UploadImage",
        addUrl: "/User/Add",
        updateUserTypeUrl: "/User/UpdateUserType",
        resetPwdUrl: "/Login/UpdatePassword",
        deleteUser: "/User/DeleteUser"
    };
    var opt = {};

    var columns = [{
        field: 'state',
        radio: true
    }, {
        title: '行号',
        field: 'number',
        align: 'center',
        hide: true,
        formatter: plscommon.tableNumber
    }, {
        title: '用户ID',
        field: 'Id',
    }, {
        title: '头像',
        field: 'PhotoGraph',
        align: 'center',
        formatter: function (value, rows, index) {
            if (value === null) {
                return '<div><img src="/Content/images/default.jpg" style="width:40px;height:40px;"></div>';
            } else {
                return '<div><img src="' + value + '" style="width:40px;height:40px;"></div>';
            }
        }
    }, {
        title: '姓名',
        field: 'UserName',
        align: 'center',
    }, {
        title: '用户类型',
        field: 'UserType',
        align: 'center',
        formatter: function (value, rows, index) {
            var result = returnUserType(value);
            return '<div id="UserType_' + rows.Id + '">' + result + '</div>';
        }
    }, {
        title: '昵称/手机号',
        field: 'NickName',
        align: 'center',
        formatter: function (value, rows, index) {
            var NickName = rows.NickName == null ? "" : rows.NickName;
            var Tel = rows.Tel == null ? "" : rows.Tel;
            return NickName + "<br />" + Tel;
        }
    }, {
        title: 'OpenId/邀请码',
        field: 'OpenId',
        align: 'center',
        formatter: function (value, rows, index) {
            var OpenId = rows.OpenId == null ? "" : rows.OpenId;
            var InvitationCode = rows.InvitationCode == null ? "" : rows.InvitationCode;
            return OpenId + "<br />" + InvitationCode;
        }
    }, {
        title: '性别',
        field: 'Gender',
        align: 'center',
        formatter: function (value, rows, index) {
            return returnUserGender(value);
        }
    }, {
        title: '创建时间',
        field: 'CreateTime',
        align: 'center'
    }];

    var initTable = function () {
        plscommon.bootstraptable({
            id: "#userinfo",
            url: defaults.listUrl,
            queryParams: queryParams,
            uniqueId: "Id",
            columns: columns
        });
    }

    var queryParams = function (params) {
        return {
            offset: params.offset,             //后台计算显示数据信息
            pagesize: params.limit,            //每页显示多少行
            nickname_search: $("#nickname_search").val(),
            tel_search: $("#tel_search").val(),
        };
    };

    var initDropDownList = function () {
        plscommon.dropDownList("#UserType", defaults.getuserTypeUrl, 1);
        plscommon.dropDownList("#user_type", defaults.getuserTypeAllUrl, 1);
    }

    var clickEvent = function () {
        $("#btnQueryList").on("click", function () { btnQueryList(); });                        //按条件查询结果
        $("#btnReset").on("click", function () { btnReset(); });                                //清空文本框信息

        $("#file").on("change", function (e) { btnUploadFile(e) });                           //上传图片
        $("#btnAddDialog").on("click", function () { btnAddDialog(); });                        //添加用户弹出层
        $("#btnAddEditOK").on("click", function () { btnAddEditOK(); });                        //添加用户

        $("#btnUpdateUserTypeDialog").on("click", function () { btnUpdateUserTypeDialog(); });  //更改用户类别弹出框
        $("#btnUpdateUserType").on("click", function () { btnUpdateUserType(); });              //更改用户类别

        $("#btnQueryAddRess").on("click", function () { btnQueryAddRess(); });                  //查看用户收货地址
        $("#btnInvitationCode").on("click", function () { btnInvitationCode(); });              //查看用户邀请人

        $("#btnResetPwd").on("click", function () { btnResetPwd(); });                          //弹出重置密码提示框弹出框
        $("#btnResetUserPwd").on("click", function () { btnResetUserPwd(); });                  //重置密码

        $("#btnDeleteUserDialog").on("click", function () { btnDeleteUserDialog() });           //删除用户弹出框
        $("#btnDeleteUser").on("click", function () { btnDeleteUser() });                       //删除用户

        $("#btnDetailDialog").on("click", function () { btnDetailDialog(); });                  //用户详情
    };

    var btnQueryList = function () {
        plscommon.refreshTable("userinfo");
    }

    var btnReset = function () {
        plscommon.resetFrom("formSearch");
    }

    var btnUploadFile = function (e) {
        var file = e.target.files[0] || e.dataTransfer.files[0];
        if (file) {
            var reader = new FileReader();
            reader.onload = function () { }
            reader.readAsDataURL(file);
        }
        var path = plscommon.uploadFile("post", defaults.uploadUrl, document.getElementById("file").files[0]);
        $("#PhotoGraph").attr("src", path);
    }

    var btnAddDialog = function () {
        $('#AddEditModal').modal();
        plscommon.resetFrom("userOperation");

        $("#HeadTitle").text("用户信息添加");
        $("#PhotoGraph").attr("src", "");
        $("input[type=radio][name='Gender'][value='3']").prop("checked", "checked");
        $("#UserType").selectpicker("val", -1);
        opt.type = 1;
    }

    var btnAddEditOK = function () {
        //读取form表单中的值并且进行验证
        var data = plscommon.deleteByValue($("#userOperation").serializeArray(), "Id");
        data = plscommon.transitionArray(data);
        data.Password = data.Password;
        data.PhotoGraph = $("#PhotoGraph").attr("src");
        if (!checkData(data)) {
            return false;
        }

        $("#btnAddEditOK").prop("disabled", true);
        if (opt.type == 1) {
            plscommon.ajax({
                disableId: "btnAddEditOK",
                url: defaults.addUrl,
                type: "POST",
                data: data,
                success: function () {
                    $('#AddEditModal').modal('hide');
                    plscommon.refreshTable("userinfo");
                }
            });
        }
    }

    var btnUpdateUserTypeDialog = function () {
        //必须选中一条才能弹出
        var data = plscommon.dialogWaring('userinfo', 'UpdateUserTypeModal', 'updateUserType');
        if (!data.Id) {
            return false;
        }

        $('#UpdateUserTypeModal').modal();
        plscommon.resetFrom("userOperation");
        $("#nick_name").val(data.NickName);
        $("#updatetype_id").val(data.Id);
        $("#user_type").selectpicker("val", data.UserType);
    }

    var btnUpdateUserType = function () {
        var data = plscommon.deleteByValue($("#updateUserType").serializeArray(), "Id");
        data = plscommon.transitionArray(data);
        if (data.user_type == -1) {
            plscommon.warningMessage("请选择用户分类", 4000);
            return false;
        }
        $("#btnUpdateUserType").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnUpdateUserType",
            url: defaults.updateUserTypeUrl,
            type: "POST",
            data: { id: data.updatetype_id, user_type: data.user_type },
            success: function () {
                $('#UpdateUserTypeModal').modal('hide');
                $("#UserType_" + data.updatetype_id).html(returnUserType(data.user_type));
            }
        });
    }

    var btnQueryAddRess = function () {
        var data = plscommon.dialogWaring('userinfo', 'QueryAddRess', 'QueryAddRessOperation');
        if (!data.Id) {
            return false;
        }
        $("#HeadTitle_Address").text("(" + data.NickName + ")用户收货地址");

        //发送请求调用查询后台返回数据
        $("#btnQueryAddRess").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnQueryAddRess",
            url: defaults.getAddRessByUserIdUrl,
            type: "GET",
            data: { id: data.Id },
            success: function () {
                var data = this.data;
                if (data.length > 0) {
                    $("#AddRess").show();
                    $("#AddRessNo").hide();

                    //不为空写入查询出来的内容
                    $("#AddRess table tbody").html("");
                    var tbody_tr = "";
                    $.each(data, function (i, item) {
                        var defaultMark = item.DefaultMark == 1 ? "默认" : "非默认";
                        tbody_tr += "<tr><td>" + item.ContactName + "</td><td>" + item.Contact + "</td><td>" + item.Address + "</td>"
                            + "<td>" + defaultMark + "</td>"
                            + "<td>" + item.CreateTime + "</td></tr>";
                    });
                    $("#AddRess table tbody").append(tbody_tr);

                } else {
                    $("#AddRess").hide();
                    $("#AddRessNo").show();
                }
            }
        });
    }

    var btnInvitationCode = function () {
        var data = plscommon.dialogWaring('userinfo', 'QueryUserInvitation', 'QueryUserInvitationOperation');
        if (!data.Id) {
            return false;
        }
        $("#HeadTitle_Address").text("(" + data.NickName + ")用户邀请的用户信息");

        //发送请求调用查询后台返回数据
        $("#btnInvitationCode").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnInvitationCode",
            url: defaults.getUserInvitationByUserIdUrl,
            type: "GET",
            data: { id: data.Id },
            success: function () {
                var data = this.data;
                if (data.length > 0) {
                    $("#UserInvitation").show();
                    $("#UserInvitationNo").hide();

                    //不为空写入查询出来的内容
                    $("#UserInvitation table tbody").html("");
                    var tbody_tr = "";
                    $.each(data, function (i, item) {
                        tbody_tr += "<tr><td>" + item.NickName + "</td><td>" + item.AddType + "</td><td>" + item.ContentSource + "</td>"
                            + "<td>" + item.CreateTime + "</td></tr>";
                    });
                    $("#UserInvitation table tbody").append(tbody_tr);

                } else {
                    $("#UserInvitation").hide();
                    $("#UserInvitationNo").show();
                }
            }
        });
    }

    var btnResetPwd = function () {
        var data = plscommon.dialogWaring('userinfo', 'ResetPwdModal', 'reset_pwd_Operation');
        if (!data.Id) {
            return false;
        }
        $("#reset_user_id").val(data.Id);
        $("#ResetPwd_Head_Title").text(data.NickName);
    }

    var btnResetUserPwd = function () {
        var pwd = $("#current_password").text();

        $("#btnResetUserPwd").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnResetUserPwd",
            url: defaults.resetPwdUrl,
            type: "POST",
            data: { id: $("#reset_user_id").val(), password_new: pwd },
            success: function () {
                $('#ResetPwdModal').modal('hide');
            }
        });
    }

    var btnDeleteUserDialog = function () {
        var data = plscommon.dialogWaring('userinfo', 'DeleteEditModal', 'user_Delete');
        if (!data.Id) {
            return false;
        }
        $("#delete_user_id").val(data.Id);
        $("#Delete_Head_Title").text(data.NickName);
        $("#Delete_Head_Title_OK").text(data.NickName);
    }

    var btnDeleteUser = function () {
        if ($("#delete_user_id").val() == "") {
            plscommon.warningMessage("请您选择需要删除的数据", 4000);
            return false;
        }

        $("#btnDeleteUser").prop("disabled", true);
        plscommon.ajax({
            disableId: "btnDeleteUser",
            url: defaults.deleteUser,
            type: "POST",
            data: { id: $("#delete_user_id").val() },
            success: function () {
                $('#DeleteEditModal').modal('hide');
                $("#userinfo").bootstrapTable('refresh');
            }
        });
    }

    var btnDetailDialog = function () {
        var data = plscommon.dialogWaring('userinfo', 'DetailModal', 'userDetail');
        if (!data.Id) {
            return false;
        }

        plscommon.ajax({
            url: defaults.getById,
            type: "GET",
            data: { Id: data.Id },
            success: function () {
                var data = this.data;
                $("#Detail_NickName").val(data.NickName);
                $("#Detail_UserName").val(data.UserName);
                $("#Detail_Tel").val(data.Tel);
                $("#Detail_UserType").val(returnUserType(data.UserType));
                $("#Detail_OpenId").val(data.OpenId);
                $("#Detail_Gender").val(returnUserGender(data.Gender));
                $("#Detail_Country").val(data.Country);
                $("#Detail_City").val(data.City);
                $("#Detail_Province").val(data.Province);
                $("#Detail_InvitationCode").val(data.InvitationCode);
                $("#Detail_CreateTime").val(data.CreateTime);
                $("#Detail_PhotoGraph").attr("src", data.PhotoGraph);
            }
        });
    }

    var checkData = function (data) {
        if (!data.NickName) {
            plscommon.warningMessage("用户名不能为空，请您检查", 4000);
            return false;
        }
        if (!data.UserName) {
            plscommon.warningMessage("姓名不能为空，请您检查", 4000);
            return false;
        }
        if (data.NickName.length > 20) {
            plscommon.warningMessage("用户名只能输入1-20位", 4000);
            return false;
        }
        if (data.Password.length < 6 || data.Password.length > 20) {
            plscommon.warningMessage("密码只能输入6-20位", 4000);
            return false;
        }
        if (!data.Tel) {
            plscommon.warningMessage("手机号不能为空", 4000);
            return false;
        }
        if (data.Tel.length >= 15) {
            plscommon.warningMessage("手机号只能输入15位数以内", 4000);
            return false;
        }
        //        由于泰国采用的手机号码格式与国内不一致，所以暂时取消手机号码校验
        //        if (!plscommon.extend.phone().test(data.Tel)) {
        //            plscommon.warningMessage("手机号格式不正确，请您检查", 4000);
        //            return false;
        //        }
        if (data.UserType == -1) {
            plscommon.warningMessage("请选择用户分类", 4000);
            return false;
        }
        if (!data.PhotoGraph) {
            plscommon.warningMessage("用户头像不能为空，请选择用户头像", 4000);
            return false;
        }
        return true;
    }

    var returnUserType = function (value) {
        var result = "";
        if (value == 1) {
            result = "普通用户";
        }
        if (value == 2) {
            result = "商户";
        }
        if (value == 3) {
            result = "骑手";
        }
        if (value == 4) {
            result = "管理员";
        }
        return result;
    }

    var returnUserGender = function (value) {
        var result = "保密";
        if (value == 1) {
            result = "男";
        }
        if (value == 2) {
            result = "女";
        }
        return result;
    }

    return {
        init: function (options) {
            $.extend(defaults, options || {});
            initTable();            //初始化Table表格
            initDropDownList();       //初始化下拉控件
            clickEvent();           //触发事件
        }
    }
}());